<!-- eslint-disable array-callback-return -->
<!-- eslint-disable consistent-return -->
<template>
  <div class="uploader">
    <div
      v-show="fileList.length"
      class="list">
      <div
        v-for="(item, index) in fileList"
        :key="item.id"
        class="option img"
        @click="preview(item)">
        <i
          class="remove geek-icon"
          @click.stop="deleteRead(index)">
          &#xe656;
        </i>
        <i
          v-if="item.type === 'video'"
          class="geek-icon play-video">
          &#xe6d1;
        </i>
        <van-image
          :src="item.type === 'video' ? item.videoUrl : item.url"
          fit="cover"
          lazy-load>
          <template v-slot:loading>
            <van-loading
              type="spinner"
              size="20" />
          </template>
        </van-image>
      </div>
    </div>
    <div class="uploader-box">
      <van-uploader
        v-model="fileList"
        :accept="acceptType"
        :preview-image="false"
        :multiple="maxfile > 1"
        :max-count="maxfile"
        :before-read="beforeRead">
        <template #default>
          <div class="lasticon">
            <i class="geek-icon">&#xe61f;</i>
            <!-- <p>图片/视频</p> -->
          </div>
        </template>
      </van-uploader>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { showImagePreview, showToast } from 'vant';
import playVideo from '@/components/play-video';
import api from '@/api';
import { useRoute } from 'vue-router';
const route = useRoute();
interface Props {}
const maxfile = ref(1);
const props = withDefaults(defineProps<Props>(), {});
const fileList: any = ref([]);

const acceptType = ref<string>('image/*');
// 接收的函数
const emits = defineEmits(['uploadUrl']);
// 验证仅存在1个视频
const testandverify = () => {
  // 验证
  if (route.query.type === 'image') {
    acceptType.value = 'image/*';
    maxfile.value = 1;
  }
  if (route.query.type === 'Video') {
    acceptType.value = 'video/*';
    maxfile.value = 1;
  }
  if (route.query.type === 'allImage') {
    acceptType.value = 'image/*';
    maxfile.value = 3;
  }
  console.log(maxfile.value);
};

const setUploadPart = async (blob: any) => {
  if (Array.isArray(blob)) {
    for (let i = 0; i < blob.length; i++) {
      setUploadPart(blob[i]);
    }
    return;
  }
  const sliceSize = 5 * 1024 * 1024;
  // 文件大小
  const fileSize = blob.size;
  // 文件大小限制为最大2个G，可根据需求修改
  const maxfilesizes = 2 * 1024 * 1024 * 1024;
  const id = new Date().valueOf();
  // 文件名
  const fileName = blob.name;
  // 计算文件切片总数，Math.ceil向上取整数
  const totalSlice = Math.ceil(fileSize / sliceSize) || 1;

  if (fileSize <= maxfilesizes) {
    for (let i = 0; i < totalSlice; i++) {
      const start = i * sliceSize;
      const chunk = blob.slice(start, Math.min(fileSize, start + sliceSize));
      const formData = new FormData();
      formData.append('multipartFile', chunk);
      formData.append('id', id);
      formData.append('fileName', fileName);
      formData.append('index', i + 1);
      formData.append(' total', totalSlice);
      const res: any = await api.setUploadPart(formData);
      if (res.success && res.data.state === 200) {
        api
          .setMergePart({
            fileName,
            id
          })
          .then((data: any) => {
            if (data.success) {
              fileList.value.push({
                url: data.data.data.safeUrl,
                videoUrl: data.data.data.datas.imageUrl,
                type: data.data.data.datas.imageUrl ? 'video' : 'image'
              });
              testandverify();
              emits('uploadUrl', fileList.value);
            }
          });
      }
    }
  } else {
    showToast({
      message: '文件大小不能超过2GB',
      position: 'top'
    });
  }
};
// 上传前
const beforeRead = (file: any) => {
  setUploadPart(file);
  return false;
};
// 删除
const deleteRead = (index: number) => {
  fileList.value = fileList.value.filter((item: any, i: number) => i !== index);
  testandverify();
  console.log('删除', fileList.value);
  emits('uploadUrl', fileList.value);
  return true;
};
testandverify();

const preview = (item: any) => {
  console.log(item.url);
  // 预览图片
  if (item.type === 'image') {
    const list = fileList.value.filter((d: any) => d.type === 'image').map((d: any) => d.url);
    showImagePreview({
      images: list,
      startPosition: list.findIndex((d: any) => d === item.url)
    });
  } else {
    // 预览吗视频
    playVideo(item.url);
  }
};
</script>

<style lang="scss" scoped>
.uploader {
  padding: 40px 0;
  .lasticon {
    margin-right: 16px;
    width: 710px;
    height: 400px;
    background: #e4e4e4;
    border-radius: 10px;
    border: solid 1px #e2e2e2;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;

    .geek-icon {
      font-size: 100px;
      line-height: 400px;
      color: #ccc;
    }
    p {
      font-size: 18px;
      color: #bfbfbf;
    }
  }

  .list {
    padding-bottom: 0.24rem;
    .option {
      display: inline-block;
      position: relative;
      vertical-align: top;
      width: 1.55rem;
      height: 1.55rem;
      margin: 0.16rem 0.16rem 0 0;
      border-radius: 0.03rem;
      &:nth-child(4n) {
        margin-right: 0;
      }
      .remove {
        position: absolute;
        z-index: 10;
        right: 0;
        top: 0;
        width: 0.32rem;
        height: 0.32rem;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(0, 0, 0, 0.6);
        transform: translate(50%, -50%);
        font-size: 0.12rem;
        color: #fff;
      }
      .play-video {
        z-index: 10;
        transform: translate(-50%, -50%) scale(0.7);
      }
      :deep(.van-image) {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 0.03rem;
      }
    }
  }
  .uploader-box {
    display: flex;
  }
}
</style>
